package chen.yi.component.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * redis模板配置
 * @author huat
 **/
@Configuration
public class RedisTemplateConfig {

    public final RedisProperties redisProperties;

    @Autowired
    public RedisTemplateConfig(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @Value("${spring.data.redis.lettuce.pool.time-between-eviction-runs:2000}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.data.redis.password:}")
    private String password;
    @Value("${spring.data.redis.cluster.max-redirects:3}")
    private Integer maxRedirects;
    @Value("${spring.data.redis.lettuce.cluster.refresh.period:60}")
    private Integer period;
    @Value("${spring.data.redis.timeout:60}")
    private Integer timeout;
    @Value("${chen-yi.redis.key-prefix}")
    private  String keyPrefix;

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        lettuceConnectionFactory.setShareNativeConnection(false);
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        //使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        // 反序列化时忽略多余字段
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //序列化忽略为null字段
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        jackson2JsonRedisSerializer.serialize(mapper);
        PrefixRedisSerializer stringRedisSerializer = new PrefixRedisSerializer(keyPrefix);
        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        lettuceConnectionFactory.afterPropertiesSet();
        template.afterPropertiesSet();
        return template;
    }


    @Bean
    public GenericObjectPoolConfig poolConfig() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
        config.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
        config.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
        config.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().toMillis());
        config.setTimeBetweenEvictionRuns(Duration.ofMillis(timeBetweenEvictionRunsMillis));
        return config;
    }


    /**
     * sentinel 哨兵模式configuration
     */
    @Bean
    @ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "sentinel")
    public RedisSentinelConfiguration redisConfigurationModeSentinel() {
        RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration();
        redisConfig.setMaster(redisProperties.getSentinel().getMaster());
        if (redisProperties.getSentinel().getNodes() != null) {
            List<RedisNode> sentinelNode = new ArrayList<RedisNode>();
            for (String sen : redisProperties.getSentinel().getNodes()) {
                String[] arr = sen.split(":");
                sentinelNode.add(new RedisNode(arr[0], Integer.parseInt(arr[1])));
            }
            redisConfig.setPassword(redisProperties.getPassword());
            redisConfig.setSentinelPassword(redisConfig.getPassword());
            redisConfig.setSentinels(sentinelNode);
            redisConfig.setDatabase(redisProperties.getDatabase());
        }
        return redisConfig;
    }

    /**
     * singleten单机 模式configuration
     */
    @Bean
    @ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "singleten")
    public RedisStandaloneConfiguration redisConfigurationModeSingleten() {
        RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
        standaloneConfiguration.setHostName(redisProperties.getHost());
        standaloneConfiguration.setPassword(redisProperties.getPassword());
        standaloneConfiguration.setPort(redisProperties.getPort());
        standaloneConfiguration.setDatabase(redisProperties.getDatabase());
        return standaloneConfiguration;

    }

    /**
     * cluster 模式configuration
     */
    @Bean
    @ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "cluster")
    public RedisClusterConfiguration redisClusterConfigurationModeCluster() {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
        redisClusterConfiguration.setPassword(redisProperties.getPassword());
        return redisClusterConfiguration;
    }

    /**
     * singleten单机 模式redisConnectionFactory
     */
    @Bean("redisConnectionFactory")
    @ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "singleten")
    public LettuceConnectionFactory redisConnectionFactoryModeSingleten(@Qualifier("poolConfig") GenericObjectPoolConfig config,
                                                                        RedisStandaloneConfiguration redisStandaloneConfiguration) {//注意传入的对象名和类型RedisSentinelConfiguration
        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
        return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfiguration);
    }


    /**
     * sentinel哨兵 模式redisConnectionFactory
     */
    @Bean("redisConnectionFactory")
    @ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "sentinel")
    public LettuceConnectionFactory redisConnectionFactoryModeSentinel(@Qualifier("poolConfig") GenericObjectPoolConfig config,
                                                                       RedisSentinelConfiguration redisConfig) {//注意传入的对象名和类型RedisSentinelConfiguration
        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
        return new LettuceConnectionFactory(redisConfig, clientConfiguration);
    }


    /**
     * cluster 模式redisConnectionFactory
     */
    @Bean("redisConnectionFactory")
    @ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "cluster")
    public LettuceConnectionFactory redisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
        RedisProperties.Cluster cluster = redisProperties.getCluster();
        List<String> nodes = cluster.getNodes();
        List<RedisNode> listNodes = new ArrayList();
        for (String node : nodes) {
            String[] ipAndPort = node.split(":");
            RedisNode redisNode = new RedisNode(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
            listNodes.add(redisNode);
        }
        redisClusterConfiguration.setClusterNodes(listNodes);
        redisClusterConfiguration.setPassword(password);
        redisClusterConfiguration.setMaxRedirects(maxRedirects);
        // 配置集群自动刷新拓扑
        ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓扑
                .enableAllAdaptiveRefreshTriggers() //根据事件刷新拓扑
                .build();

        ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                //redis命令超时时间,超时后才会使用新的拓扑信息重新建立连接
                .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period)))
                .topologyRefreshOptions(topologyRefreshOptions)
                .build();
        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(timeout))
                .poolConfig(poolConfig())
                .readFrom(ReadFrom.REPLICA_PREFERRED) // 优先从副本读取
                .clientOptions(clusterClientOptions)
                .build();
        return new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);
    }
}
